package com.hc.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import java.util.HashMap;
import java.util.Map;

/**
 * 编写工具类用于产生和校验JWT
 */
public class JwtUtil {

    private String secret = "2edf2b0c08c54be3a424116119a6d461"; //密钥
    private int expireSeconds =  30*60*1000; // token的过期时间;

    //产生JWT
    public String createJWT(int id, String account, int roleId){
        DateTime now = DateTime.now();
        DateTime newTime = now.offsetNew(DateField.SECOND, expireSeconds);

        Map<String,Object> payload = new HashMap<String,Object>();
        //签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        //过期时间
        payload.put(JWTPayload.EXPIRES_AT, newTime);
        //生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);
        //载荷
        payload.put("id", id);
        payload.put("account", account);
        payload.put("roleId", roleId);

        String token = JWTUtil.createToken(payload, secret.getBytes());

        return token;
    }

    //校验JWT
    public boolean verifyJWT(String jwt){
        JWT token = JWTUtil.parseToken(jwt);
        boolean verifyKey = token.setKey(secret.getBytes()).verify();

        return verifyKey;
    }

    //获取JWT中用户自定义的数据 解析
    public Object getInfo(String jwt, String name){
        JWT token = JWTUtil.parseToken(jwt);
        return token.getPayload(name);
    }
}
